﻿using adb;
using Masuit.Tools.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;

namespace PowerStation.Controllers
{
    /// <summary>
    /// 登陆
    /// </summary>
    [AllowAnonymous]
    public class LoginController : BaseApi<LoginController>
    {
        
        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="_config"></param>
        /// <param name="log"></param>
        /// <param name="db"></param>
        /// <param name="content"></param>
        /// <param name="configuart"></param>
        public LoginController(IHttpContextAccessor content) : base(content)
        {
        }



        /// <summary>
        /// 颁发令牌接口
        /// </summary>
        /// <param name="account">登陆账号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [HttpGet]
        public ResultApi<string> GetJwtToken(string account, string password)
        {
            var model = this._db.tUser.FirstOrDefault(x => x.account == account);
            if (model == null)
            {
                return ResultApi.error("","账号不存在");
            }

            if (password.MDString() != model.password)return ResultApi.error("","密码错误");
            
            //获取在配置文件中获取Jwt属性设置
            string key = this.configuart["JwtSettings:securityKey"];//Appsettings.app(new string[] { "JwtSettings", "securityKey" });
            string issuer = this.configuart["JwtSettings:Issuer"];//Appsettings.app(new string[] { "JwtSettings", "Issuer" });
            string audience = this.configuart["JwtSettings:Audience"];//Appsettings.app(new string[] { "JwtSettings", "Audience" });
            var claims = new List<Claim> {
                //下面的都是自定义字段，可以任意添加到Claim作为信息共享
                new Claim(ClaimTypes.NameIdentifier,model.userId+""),
                new Claim(ClaimTypes.Name,model.userName),
            };
            //创建授权的token类
            SecurityToken securityToken = new JwtSecurityToken(
                issuer: issuer, //签发人
                audience: audience, //受众
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key)), SecurityAlgorithms.HmacSha256), //秘钥

                //创建过期时间
                expires: DateTime.Now.AddDays(1), //过期时间 一小时之后过期

                //自定义JWT字段
                claims: claims
                );
            var token = new JwtSecurityTokenHandler().WriteToken(securityToken);
            Response.Cookies.Append("auth",token);
            //返回请求token
            return ResultApi.ok(token);
        }
    }
}
